﻿using System;
using System.Collections.Generic;
using ACSR.SqlServer.AddIn.Core.Controllers;
using EnvDTE;
using ProcedureList.Library.Domain;
using ProcedureList.Library.UI;

namespace SSMSProcedureList.Controllers
{
    public class ProcedureListController : AddInController
    {
        private dynamic _CommandInstance;

        protected override void InternalOnConnectionCompleted()
        {
            LogMessage("ProcedureListController: InternalOnConnectionCompleted");
        }

        protected override void InternalOnStartupCompleteCompleted(ref Array custom)
        {
            try
            {
                var bar = CreateCommandBar("ProcedureList");
                this._CommandInstance = AddCommand(bar, "ProcedureList", "Procedure List", "Show Procedures", 13);
                this._CommandInstance.Bindings = "Global::CTRL+G";
                LogMessage("ProcedureListController: InternalOnStartupCompleteCompleted");
            }
            catch (Exception e)
            {
                LogError("Error ProcedureListController.InternalOnStartupCompleteCompleted: " + e.Message);
            }
        }

        private Cache _cache = new Cache();

        protected override void InternalExec(string CmdName, EnvDTE.vsCommandExecOption ExecuteOption, ref object VariantIn, ref object VariantOut, ref bool Handled)
        {
            var activeWindow = this.AddInInstance.DTE.ActiveWindow;
            if (this.IsTextWindow(activeWindow))
            {
                var savedOffset = activeWindow.Selection.ActivePoint.AbsoluteCharOffset;
                activeWindow.Selection.SelectAll();
                var text = activeWindow.Selection.Text;
                activeWindow.Selection.Cancel();
                activeWindow.Selection.MoveToAbsoluteOffset(savedOffset);

                var methods = _cache.GetMethods(activeWindow, text);

                var frm = new FormProcedureList();
                frm.BindMethods(methods);
                frm.ShowDialog();
                if (frm.SelectedMethod != null)
                {
                    activeWindow.Selection.GotoLine(frm.SelectedMethod.Position);
                }
            }
        }

        

       
    }
}
